package me.skyun.androidarch.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import me.skyun.androidarch.R;
import me.skyun.androidarch.common.Utils;

/**
 * Created by skyun on 17/8/22.
 */

public class ImageViewEx extends AppCompatImageView {

    private boolean mIsRounded = false;
    private Paint mPaint = new Paint();

    public ImageViewEx(Context context) {
        this(context, null);
    }

    public ImageViewEx(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ImageViewEx(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint.setAntiAlias(true);
        TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.ImageViewEx, defStyleAttr, 0);
        mIsRounded = a.getBoolean(R.styleable.ImageViewEx_isRound, false);
        a.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mIsRounded) {
            RectF viewRect = new RectF(0, 0, getWidth(), getHeight());
            int saveFlags = Canvas.MATRIX_SAVE_FLAG
                    | Canvas.CLIP_SAVE_FLAG
                    | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
                    | Canvas.FULL_COLOR_LAYER_SAVE_FLAG
                    | Canvas.CLIP_TO_LAYER_SAVE_FLAG;
            canvas.saveLayer(viewRect, mPaint, saveFlags);
            canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            Drawable drawable = getDrawable();
            if (drawable != null && drawable instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                canvas.drawBitmap(bitmap, 0, 0, mPaint);
            }
            mPaint.setXfermode(null);
            canvas.restore();
        }
    }
}

